<template>
  <div class="product-add">
    <DynamicForm
        ref="dynamicFormRef"
        :rulesForm="state.productAdd"
        :rules="state.rules"
        :refresh="state.refresh"
        @click="callBack"
    />
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, defineEmits, reactive} from "vue";
import {ElMessage} from "element-plus";
import DynamicForm from "@/components/layout/form/dynamic-form.vue";

import {
  productAddForms, //表单
  productAddRules, //验证规则
} from "@/assets/script/middle/forms/product/add-form";

import {
  insertApi,
  listCustomerPageApi,
  findByIdApi,
  modifyApi,
} from "@/api/product";
import {listConstByDictionaryCodesApi} from "@/api/dictionary";

import {useRoute} from "vue-router";

const emits = defineEmits<{ (e: "appClick", data: object): void }>();

const router = useRoute();
const state = reactive({
  productAdd: JSON.parse(JSON.stringify(productAddForms)) as any,
  rules: productAddRules as any,
  refresh: 0 as number,
  bed: {} as any,
});

const dynamicFormRef = ref(DynamicForm);
const deviceFunctionList = ref([]) as any;
const supplierList = ref([]) as any;
const card = state.productAdd[0].card;

onMounted(() => {
  listConstByDictionaryCodesApi([
    "device_category",
    "spec_version",
    "spec_type",
    "device_function",
  ]).then((data) => {
    console.log(data);
    //产品类型数据
    const specType = card.find((f: any) => f.name === "deviceType");
    specType.options = [];
    //产品版本
    const specVersion = card.find((f: any) => f.name === "specVersion");
    specVersion.options = [];
    //规格
    const typeCodes = card.find((f: any) => f.name === "typeCode");
    typeCodes.options = [];
    data?.forEach((res = {} as any) => {
      if (res.dictionaryCode == "device_category") {
        specType.options?.push({
          label: res.constName,
          value: res.constCode,
        });
      }
      if (res.dictionaryCode == "spec_version") {
        specVersion.options?.push({
          label: res.constName,
          value: res.constCode,
        });
      }
      if (res.dictionaryCode == "spec_type") {
        typeCodes.options?.push({
          label: res.dictionaryName,
          value: res.constCode,
        });
      }
      if (res.dictionaryCode == "device_function") {
        deviceFunctionList.value?.push({
          label: res.constName,
          value: res.constCode,
        });
      }
      //设备功能规格数据
      const functionLists = card.find((f: any) => f.name === "functionList");
      if (functionLists) {
        functionLists.options = deviceFunctionList.value;
      }
    });
  });

  listCustomerPageApi({
    pageIndex: 1,
    pageSize: 100,
  }).then((data) => {
    if (data.code == 0) {
      //设备功能规格数据
      data.data?.forEach((res: any) => {
        if (res.customerType == "supplier") {
          supplierList.value.push({
            label: res.name,
            value: res.code,
            address: res.address,
            telephone: res.telephone,
            contacts: res.contacts,
          });
        }
      });
      const supplierLists = card.find((f: any) => f.name === "supplierList");
      if (supplierLists) {
        supplierLists.options = supplierList.value;
      }
    }
  });
  //判断是否是编辑
  if (router.query && router.query.id) {
    findByIdFun(router.query.id as any);
  }
});
//查询数据
const findByIdFun = async (id: string) => {
  findByIdApi({id}).then((data: any) => {
    if (data.code == 0) {
      let datas = data.data;
      state.bed = data.data;
      let supplierLists = supplierList.value.find(
          (f: any) => f.value === state.bed.supplierCode
      );
      card.forEach((e: any) => {
        if (!e.line) {
          switch (e.name) {
            case "functionList":
              //支持监测信息
              e[e.name] = state.bed["functionList"];
              // eslint-disable-next-line no-case-declarations
              const functionLists = [] as any;
              datas.functionList.forEach((res: any) => {
                let fun = deviceFunctionList.value.find(
                    (f: any) => f.value === res.functionCode
                );
                if (fun) {
                  functionLists.push(fun.value);
                }
              });
              card.find((f: any) => f.name === "functionList")["functionList"] =
                  functionLists;
              break;
            case "supplierList":
              //供应商
              e[e.name] = state.bed["supplierCode"];
              break;
            case "address":
              //联系地址
              if (supplierLists) {
                e[e.name] = supplierLists.address;
              }
              break;
            case "contacts":
              //联系人
              if (supplierLists) {
                e[e.name] = supplierLists.contacts;
              }
              break;
            case "telephone":
              //联系电话
              if (supplierLists) {
                e[e.name] = supplierLists.telephone;
              }
              break;
            default:
              e[e.name] = state.bed[e.name];
              break;
          }
        }
      });
      state.refresh = Math.random();
    }
  });
};

const callBack = (data: any) => {
  switch (data.type || "") {
      //供应商选择的数据
    case "supplierList":
      let formData = dynamicFormRef.value.getData();
      for (let d in formData) {
        card.find((f: any) => f.name === d)[d] = formData[d];
      }
      let supplierLists = supplierList.value.find(
          (f: any) => f.value === data.data
      );
      if (supplierLists) {
        card.find((f: any) => f.name === "address")["address"] =
            supplierLists.address;
        card.find((f: any) => f.name === "contacts")["contacts"] =
            supplierLists.contacts;
        card.find((f: any) => f.name === "telephone")["telephone"] =
            supplierLists.telephone;
        console.log('callBack', state.refresh)
      }
      break;
      //提交表单
    case "submit":
      let datas = data.data;
      console.log(datas);
      let DeviceFunctions = ref([]) as any;
      datas.functionList?.forEach((res: any) => {
        let availableJson = deviceFunctionList.value.find(
            (f: any) => f.value === res
        );
        if (availableJson) {
          DeviceFunctions.value.push({
            functionName: availableJson.label,
            functionCode: availableJson.value,
          });
        }
      });

      let parame = datas;
      parame.imageUrl = datas.imageUrl || null; //产品图片
      parame.typeName = datas.typeCodeName; //规格类型名称
      parame.functionList = DeviceFunctions.value; //设备功能规格数据
      parame.remark = datas.remark || null; //备注
      parame.supplierName = datas.supplierListName; //供应商
      let supplierListss = supplierList.value.find(
          (f: any) => f.value === datas.supplierList
      );
      if (supplierListss) {
        parame.supplierCode = supplierListss.value; //供应商编码
      }
      insertFun(parame);
      break;
  }
};
//新增产品
const insertFun = (params: any) => {
  //判断是否是编辑;
  if (router.query && router.query.id) {
    params.id = router.query.id;
    console.log(params);
    modifyApi(params).then((data: any) => {
      if (data.code == 0) {
        ElMessage.success("修改成功");
        state.refresh = Math.random();
        emits("appClick", {type: "closeTab", data: router.path});
      }
    });
  } else {
    console.log(params);
    //新增
    insertApi(params).then((data: any) => {
      if (data.code == 0) {
        ElMessage.success("新增成功");
        state.refresh = Math.random();
        emits("appClick", {type: "closeTab", data: router.path});
      }
    });
  }
};
</script>
